﻿using DotNetCore.CAP;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WebApplication3.Data;
using WebApplication3.Data.Entities;
using WebApplication3.Helpers;
using WebApplication3.Interfaces;

namespace WebApplication3.Services
{
	public class SFOrderService
	{
		 IAsyncRepository<OrderEntity> _orderEntityRepository;
		private readonly DotNetCore.CAP.ICapPublisher capPublisher; 

		public SFOrderService(IAsyncRepository<OrderEntity> orderEntityRepository,
			 DotNetCore.CAP.ICapPublisher capPublisher 
			)
		{
			this._orderEntityRepository = orderEntityRepository;
			this.capPublisher = capPublisher; 
		}
		#region 内部类
		private class QueryOrder
		{
			public int dev_id { get; set; }

			public string order_id { get; set; }

			public int order_type { get; set; }

			public string shop_id { get; set; }

			public int shop_type { get; set; }

			public long push_time { get; set; }
		}
		public class CancelOrder
		{
			public int dev_id { get; set; }

			public string order_id { get; set; }

			public int order_type { get; set; }

			public string shop_id { get; set; }

			public int shop_type { get; set; }

			public string cancel_reason { get; set; }

			public long push_time { get; set; }

			public string result { get; set; }
		}

		#endregion

		/// <summary>
		/// 取消订单
		/// </summary>
		/// <param name="orderId"></param>
		/// <returns></returns>
		public async Task<string> CancelAsync(int orderId,string cancel_reason)
		{
			var order = await this._orderEntityRepository.GetByIdAsync(orderId);
			if (order != null)
			{
				if (order.Status == 2)
				{
					var postDataObj = new CancelOrder
					{
						dev_id = ConstData.DevId,
						order_id = orderId + "",
						shop_id = ConstData.ShopId,
						shop_type = 1,
						order_type = 2,
						push_time = DateTime.Now.ConvertDateTimeToInt(),
						cancel_reason = cancel_reason
					};
					try
					{ 
						var jsonObject = order.StatusData.DeserializeObject<JObject>();
						var sfOrderId = jsonObject["result"]["sf_order_id"].ToString();


						var postData = postDataObj.SerializeObject();
						var signChar = string.Format("{0}&{1}&{2}", postData,
						ConstData.DevId, ConstData.DevKey);
						var sign = signChar.GetMD5().GetBase64(); ;

						var result = await HttpHelper.PostUrlAsync(ConstData.ApiBaseUrl + $"/open/api/external/cancelorder?sign={sign}", postData);
						var resultUnescape = Regex.Unescape(result);

						var resultObj = resultUnescape.DeserializeObject<JObject>();

						postDataObj.result = resultUnescape;
						capPublisher.Publish("sf/Cancel", postDataObj);
					}
					catch (Exception ex)
					{
						capPublisher.Publish("/open/api/external/cancelorder", new { postDataObj, ex });
					}
					
				}
				try
				{
					order.Status = 4;
					await _orderEntityRepository.UpdateAsync(order);
					return (new { code = 0, orderModel = order }).SerializeObject();
				}
				catch (Exception ex)
				{
					capPublisher.Publish("Exception", ex);
					return (new { code = 1, ex }).SerializeObject();
				}
					 
				
				 

			}


			return (new { code = 1, orderModel = "" }).SerializeObject();
		}
		[CapSubscribe("sf/Cancel")]
		private void CancelSubscribe(CancelOrder order) {

			var result = order.result.DeserializeObject<JObject>();
			if ((int)result["error_code"] == 0)
			{
			}
			
		}

		public async Task<string> QueryAsync(int orderId) {
			var order =await this._orderEntityRepository.GetByIdAsync(orderId);
			if (order != null)
			{

				var jsonObject = order.StatusData.DeserializeObject<JObject>();

				var sfOrderId= jsonObject["result"]["sf_order_id"].ToString();

				var postDataObj = new QueryOrder {
					 dev_id=ConstData.DevId,
					  order_id= orderId+"",shop_id=ConstData.ShopId, shop_type=1, order_type=2, push_time= DateTime.Now.ConvertDateTimeToInt()

				};
				var postData = postDataObj.SerializeObject();
				var signChar = string.Format("{0}&{1}&{2}", postData,
				ConstData.DevId, ConstData.DevKey);
				var sign = signChar.GetMD5().GetBase64(); ;
				 
				var result=await HttpHelper.PostUrlAsync(ConstData.ApiBaseUrl+$"/open/api/external/listorderfeed?sign={sign}", postData);
				var resultModel = Regex.Unescape(result);

				return resultModel;

			}


			return "";
		}
	}
}
